package com.quanquan.resource.service;

import com.quanquan.resource.entity.Image;
import com.quanquan.resource.repository.imageRepository;
import exceptions.ImgException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import utils.DateUtils;
import utils.UUIDGenerator;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static org.apache.commons.lang.StringUtils.isNotEmpty;

@Service
public class ImageService {
    public static final String USER_HEAD = "userHead";
    public static final String RIGHT_AND_INTERESTS = "right_and_interests";
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    private final imageRepository imageDao;

    @Value("${image-params.imageUrl}")
    private String imageUrl;

    @Autowired
    public ImageService(imageRepository imageDao) {
        this.imageDao = imageDao;
    }


    public Image createImage(String cover, String logo, String sign, String imgUrl) {
        Image image = new Image();
        image.setId(UUIDGenerator.getUUID());
        String imgTrueUrl = imageUrl.concat(imgUrl);
        image.setImageAddress(imgTrueUrl);
        image.setCreateTime(DateUtils.parseDate2Str("yyyy-MM-dd HH:mm:ss", new Date()));
        image.setUpdateTime(DateUtils.parseDate2Str("yyyy-MM-dd HH:mm:ss", new Date()));
        image.setRemove(0);
        image.setShow(0);
        //判断封面
        if (isNotEmpty(cover)) {
            image.setCover(1);
        } else {
            image.setCover(0);
        }
        //判断logo
        if (isNotEmpty(logo)) {
            image.setLogo(1);
        } else {
            image.setLogo(0);
        }
        //判断招牌
        if (isNotEmpty(sign)) {
            image.setSign(1);
        } else {
            image.setSign(0);
        }
        imageDao.save(image);
        return image;
    }


    /**
     * 删除图片
     * 逻辑删除
     */
    public String removeImage(String imageId) throws ImgException {
        Image image = imageDao.findById(imageId).orElse(null);
        assert image != null;
        image.setRemove(1);
        imageDao.save(image);
        return "图片删除成功";
    }

    /**
     * 查询图片
     */
    public Image getImage(String imageId) {
        Image image = imageDao.findById(imageId).orElse(null);
        return image;
    }

    /**
     * 根据外键查询所有图片
     */
    public List<Image> findImages(String foreignKeyId) throws ImgException {
        List<Image> images = imageDao.findImagesByForeignKeyId(foreignKeyId);
        if (images == null) {
            throw new ImgException("图片不存在");
        }
        return images;

    }


    /**
     * 绑定图片关系
     *
     * @param imageIds
     * @param foreignKeyId
     * @param belong
     * @throws ImgException
     */
    public void bindIngRelationShip(List<String> imageIds, String foreignKeyId, String belong) throws ImgException {
        if (imageIds != null && imageIds.size() > 0) {
            for (String imageId : imageIds) {
                Image image = imageDao.findById(imageId).orElse(null);

                if (null != image) {
                    image.setForeignKeyId(foreignKeyId);
                    //设置图片归属（景点）
                    image.setBelong(belong);
                    imageDao.save(image);
                } else {
                    throw new ImgException("图片不存在");

                }

            }
        } else {
            throw new ImgException("图片Id不存在");
        }

    }

    /**
     * 更新绑定
     * @param imageIds
     * @param foreignKeyId
     * @param belong
     */
    /**
     * 绑定关联关系（补上外键）(景点) 
     */
    public void bindIngRelationShipUpdate(List<String> imageIds, String foreignKeyId, String belong) throws ImgException {
        imageDao.removeShip(foreignKeyId);
        if (imageIds != null && imageIds.size() > 0) {
            for (String imageId : imageIds) {
                Image image = imageDao.findById(imageId).orElse(null);
                if (null != image) {
                    image.setForeignKeyId(foreignKeyId);
                    //设置图片归属（景点）
                    image.setBelong(belong);
                    image.setRemove(0);
                    imageDao.save(image);
                } else {
                    throw new ImgException("图片不存在");
                }

            }
        } else {
            throw new ImgException("图片Id不存在");
        }
    }


    /**
     * 根据id查询多张图片
     *
     * @param imageIds
     * @return
     */
    public List<Image> queryImagesById(List<String> imageIds) {
        List<Image> images = new ArrayList<>();
        for (String imageId : imageIds) {
            Image image = imageDao.findById(imageId).get();
            images.add(image);
        }
        return images;
    }

    /**
     * 查看是要插入还是要更新
     *
     * @param foreignKeyId
     * @return
     */
    public boolean queryResult(String foreignKeyId) {
        List<Image> images = imageDao.findImagesByForeignKeyIdAndRemove(foreignKeyId, 0);
        if (images.size() <= 0) {
            return false;
        }
        return true;
    }

    public void removeImageByForeignKeyId(String foreignKeyId) {
        imageDao.removeShip(foreignKeyId);
    }

    /**
     * 绑定权益图片关系(只有一张)
     *
     * @param imageId
     */
    public String bindRightAndInterests(String imageId) {
        //移除所有关系
        String foreignKeyId = "huiyuanquanyi";
        imageDao.removeShip(foreignKeyId);
        Image image = imageDao.findById(imageId).orElse(null);
        if (null != image) {
            //设置图片归属（权益）
            image.setForeignKeyId(foreignKeyId);
            image.setBelong(RIGHT_AND_INTERESTS);
            image.setRemove(0);
            imageDao.save(image);

        }
        return "保存成功";
    }


    /**
     * 根据图片类型来查询图片
     */
    public Image queryRightAndInterests() throws ImgException {
        Image image = imageDao.findImageByBelongAndRemove(RIGHT_AND_INTERESTS, 0);
        if (image == null) {
            throw new ImgException("图片不存在");
        }
        return image;
    }
}
